package com.ycl.javacore.exam.limit;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TestOne {

    final static int MAX_QPS = 10;

    final static Semaphore semaphore = new Semaphore(MAX_QPS);

    public static void main(String[] args) throws InterruptedException {
        //启动一个定时执行执行任务的线程池，线程池中线程的数量为1，启动一秒后开始执行，每隔0.5秒执行一次
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {

            public void run() {
                semaphore.release(MAX_QPS);//释放曾经被占用过的坑
            }

        }, 1000, 1000, TimeUnit.MILLISECONDS);

        //创建一个有一百个线程的线程池
        ExecutorService pool = Executors.newFixedThreadPool(100);
        //提交一百个线程，去执行任务
        for (int i = 100; i > 0; i--) {
            final int x = i;
            pool.submit(new Runnable() {

                public void run() {
                    for (int j = 1000; j > 0; j--) {//不断的获取被空出来的坑
                        semaphore.acquireUninterruptibly(1);//每个线程只获取一个坑
                        remoteCall(x, 0);
                    }
                }

            });
        }
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("DONE");
    }

    private static void remoteCall(int i, int j) {
//		System.out.println(String.format("%s - %s: %d %d", new Date(),
//				Thread.currentThread(), i, j));
        System.out.println(new Date() + "   " +
                Thread.currentThread().getName() + " " + i + "  " + j);

    }

}